import React, { useEffect, useState } from "react";
import { Button, Modal, Popover, Switch, Table, Tag } from "antd";
import { DeleteOutlined, EditOutlined } from "@ant-design/icons";
import axios from "axios";
const { confirm } = Modal;

const RightList = () => {
  const columns = [
    {
      title: "ID",
      dataIndex: "id",
    },
    {
      title: "權限名稱",
      dataIndex: "title",
    },
    {
      title: "權限路徑",
      dataIndex: "key",
      render: (key) => {
        return <Tag color="orange">{key}</Tag>;
      },
    },
    {
      title: "操作",
      render: (item) => {
        return (
          <div>
            <Button
              shape="circle"
              type="primary"
              icon={<DeleteOutlined />}
              onClick={() => confirmHandle(item)}
            ></Button>
            <Popover
              content={
                <div>
                  <Switch
                    checked={item.pagepermisson}
                    onChange={()=>switchChange(item)}
                  ></Switch>
                </div>
              }
              title="頁面配置項"
              trigger={item.pagepermisson === undefined ? "" : "click"}
            >
              <Button
                shape="circle"
                type="primary"
                icon={<EditOutlined />}
                disabled={item.pagepermisson === undefined}
              ></Button>
            </Popover>
          </div>
        );
      },
    },
  ];
  const [dataSource, setDataSource] = useState([]);
  useEffect(() => {
    const apiUrl = process.env.REACT_APP_API_URL + "/rights";
    fetch(apiUrl)
      .then((res) => res.json())
      .then((res) => {
        setDataSource(res);
      });
  }, []);
  const confirmHandle = (item) => {
    confirm({
      title: "確定要刪除嗎?",
      icon: <DeleteOutlined />,
      onOk() {
        deleteHandle(item);
      },
      onCancel() {
        console.log("111");
      },
    });
  };
  const switchChange = (item) => {
      item.pagepermisson = item.pagepermisson === 1 ? 0 : 1;
      setDataSource([...dataSource]);
      const apiUrl = ""
      if(item.grade === 1){
          axios.patch(`${apiUrl}/rights/${item.id}`,{
              "pagepermisson":item.pagepermisson
          })
          }else {
          axios.patch(`${apiUrl}/children/${item.id}`,{
              "pagepermisson":item.pagepermisson
          })
      }
  };
  const deleteHandle = (item) => {
    console.log(item);
    if (item.grade === 1) {
      setDataSource(dataSource.filter((data) => data.id !== item.id));
    } else {
      let list = dataSource.filter((data) => data.id === item.rightId)[0];
      list.children = list.children.filter((data) => data.id !== item.id);
      setDataSource([...dataSource]);
    }
  };
  return (
    <div>
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{
          pageSize: 4,
        }}
      />
    </div>
  );
};

export default RightList;
